package org.pp.controller;

import org.pp.core.RestObject;
import org.pp.modules.sys.model.User;
import org.pp.modules.sys.service.UserService;
import org.pp.modules.sys.vo.UserInfo;
import org.pp.utils.HttpUtil;
import org.pp.utils.SecurityUtil;

import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;

public class PublicController extends Controller {
	@Inject
	UserService service;
		
	@ActionKey("/")
	public void index() {
		Object o = this.getSession().getAttribute("user");
		if(o == null) {
			this.login();
		}else {
			this.redirect(SecurityUtil.homeUrl());
		}		
	}
	
	@ActionKey("/login")
	public void login() {
		if(HttpUtil.isGet(getRequest())) {
			setAttr("_title", "登录");
			this.render("/view/public/login.html");
			return;
		}
		
		/**
		if(!this.validateCaptcha("captcha")) {
			renderJson(RestObject.error("验证码错误"));
			return;
		}
		*/
		String account = this.getPara("account");
		User user = service.login(account, getPara("password"));
		if(user == null) {
			renderJson(RestObject.error(service.getError()));
		}else {

			setSessionAttr("user", user);
			
			UserInfo info = new UserInfo();
			info.setAccount(account);
			info.setId(user.getId());
			info.setNickname(user.getNickname());
			String redirect = getSessionAttr("redirect");
			
			if(redirect == null ||SecurityUtil.loginUrl().equalsIgnoreCase(redirect)) {
				redirect = SecurityUtil.homeUrl();
			}
			renderJson(RestObject.success("登录成功",info, SecurityUtil.homeUrl()));
			//renderJson(RestObject.success("登录成功",info, redirect));
			removeSessionAttr("redirect");
		}
	}
	
	
	@ActionKey("/logout")
	public void logout() {
		removeSessionAttr("user");
		getSession().invalidate();
		this.redirect(SecurityUtil.homeUrl());
	}

	@ActionKey("/captcha")
	public void captcha() {
		this.renderCaptcha();
	}
}
